package com.itheima.gateway.filter;

import com.itheima.gateway.utils.AdminJwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class AuthorizeFilter implements GlobalFilter {


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取请求对象，响应对象
        ServerHttpResponse response = exchange.getResponse();
        ServerHttpRequest request = exchange.getRequest();
        System.out.println(1);
        //2.判断是否是登陆请求
        if (request.getURI().getPath().contains("login")) {
            return chain.filter(exchange);
        }


        //3.获取请求参数token
        String token = request.getHeaders().getFirst("token");
        //4.判断token是否为空
        if (StringUtils.isEmpty(token)) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //5.校验token：
        // 解析token
        // 判断是否过期、是否抛出异常
        //为什么需要判断异常：工具类调用失败是返回null还是抛出异常我们不可知，因此我们在调用工具类后，还要做一个异常捕获，防止抛出异常
        try {
            Claims claimsBody = AdminJwtUtil.getClaimsBody(token);
            int time = AdminJwtUtil.verifyToken(claimsBody);
            if (time == 1 || time == 2) {
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }
            //获得token解析后中的用户信息
            Object userId = claimsBody.get("id");
            //在header中添加新的信息
            ServerHttpRequest serverHttpRequest = request.mutate().headers(httpHeaders -> {
                httpHeaders.add("userId", userId + "");
            }).build();
            //重置header
            exchange.mutate().request(serverHttpRequest).build();

        } catch (Exception e) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //6.放行
        return chain.filter(exchange);
    }
}
